<template>
  <el-card>
    <el-form ref="formRef" :model="form" :rules="rules" size="large">
      <el-form-item label="菜单名称" prop="title">
        <el-input v-model="form.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="上级菜单">
        <el-select v-model="form.parentId" class="m-2" placeholder="请选择">
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="前端名称" prop="name">
        <el-input v-model="form.name" :disabled="onlyRead" autocomplete="off" />
      </el-form-item>
      <el-form-item label="前端图表">
        <el-input v-model="form.icon" :disabled="onlyRead" autocomplete="off" />
      </el-form-item>
      <el-form-item label="是否显示:">
        <el-radio-group class="ml-4" v-model="form.hidden">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="form.sort" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitFn">提交</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script setup lang="ts">
import router from "@/router";
import { ElMessage, FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import { useRoute } from "vue-router";
import {
  addMenuApi,
  menuListByIdApi,
  updateMenuByIdApi,
  getMenuByIdApi,
} from "./api";
// 添加请求的参数
const form = reactive<IMenuModel>({
  hidden: 0,
  icon: "",
  name: "",
  parentId: 0,
  sort: 0,
  title: "",
});
const onlyRead = ref<boolean>(false);
const list = ref<IMenuModel[]>([]);
const route = useRoute();
// 获取上级菜单
menuListByIdApi({
  pageNum: 1,
  pageSize: 100,
  parentId: 0,
}).then((res) => {
  list.value = res.data.list;
});
// 修改菜单
getMenuByIdApi(parseInt(route.query.pid as string)).then((res) => {
  const myform = ref<IMenuModel>();
  if (res.code === 200) {
    myform.value = res.data;
    // console.log("myform", myform.value);
    Object.assign(form, myform.value);
    onlyRead.value = true;
  }
});

const submitFn = () => {
  if (!onlyRead.value) {
    // 添加
    addMenuApi(form).then((res) => {
      if (res.code === 200) {
        router.push("/ums/menu");
        ElMessage.success("添加成功!");
      }
    });
  } else {
    updateMenuByIdApi(form).then((res) => {
      if (res.code === 200) {
        onlyRead.value = false;
        router.push("/ums/menu");
        ElMessage.success("修改成功!");
      }
    });
  }
};
const formRef = ref<FormInstance>();
const rules = reactive({
  title: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
  name: [{ required: true, message: "前端名称不能为空", trigger: "blur" }],
});
</script>
<style lang="less" scoped></style>
